#define _CRT_SECURE_NO_WARNINGS
#include"List.h"

ListNode* ListCreate()
{
	ListNode* guard = (ListNode*)malloc(sizeof(ListNode));
	if (guard == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	guard->next = guard;
	guard->prev = guard;
	return guard;
}

void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(pHead);
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	printf("pHead<=>");
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

ListNode* BuyListNode(LTDataType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	node->data = x;
	node->next = NULL;
	node->prev = NULL;
	return node;
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	/*ListNode* newnode = BuyListNode(x);
	ListNode* tail = pHead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = pHead;
	pHead->prev = newnode;*/
	ListInsert(pHead, x);
}

bool ListEmpty(ListNode* pHead)
{
	assert(pHead);
	if (pHead->next == pHead)
		return true;
	else
		return false;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(!ListEmpty(pHead));
	/*ListNode* tail = pHead->prev;
	pHead->prev = tail->prev;
	tail->prev->next = pHead;
	free(tail);
	tail = NULL;*/
	ListErase(pHead->prev);
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	/*ListNode* first = BuyListNode(x);
	ListNode* second = pHead->next;
	pHead->next = first;
	first->prev = pHead;
	first->next = second;
	second->prev = first;*/
	ListInsert(pHead->next, x);
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(!ListEmpty(pHead));
	/*ListNode* head = pHead->next;
	pHead->next = head->next;
	head->next->prev = pHead;
	free(head);
	head = NULL;*/
	ListErase(pHead->next);
}

size_t ListSize(ListNode* pHead)
{
	assert(pHead);
	size_t n = 0;
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		++n;
		cur = cur->next;
	}
	return n;
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	size_t n = 0;
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* newnode = BuyListNode(x);
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
	pos = NULL;
}
